package br.pucminas.virtual.validator.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;
import br.pucminas.virtual.validator.R;
import br.pucminas.virtual.validator.library.FieldValidator;
import br.pucminas.virtual.validator.library.ValidationResult;
import br.pucminas.virtual.validator.library.validators.RegexValidator;

public class ValidatorEditText extends EditText {

	// private ValidatorType validatorType;
	private FieldValidator fieldValidator;

	public ValidatorEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context, attrs);
	}

	public ValidatorEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context, attrs);
	}

	public ValidatorEditText(Context context, int validatorType) {
		super(context);
		ValidatorType fieldValidatorType = ValidatorType.values()[validatorType];
		fieldValidator = fieldValidatorType.getValidator();
	}

	private void init(Context context, AttributeSet attrs) {
		if (!this.isInEditMode()) {
			this.setTypeFromAttributeSet(context, attrs);
		}
	}

	private void setTypeFromAttributeSet(Context context, AttributeSet attrs) {
		TypedArray typedArray = context.obtainStyledAttributes(attrs,
				R.styleable.ValidatorType);

		int fieldTypeInt = typedArray.getInt(
				R.styleable.ValidatorType_validator_type, 0);

		try {
			ValidatorType validatorType = ValidatorType.values()[fieldTypeInt];
			fieldValidator = validatorType.getValidator();
			if (validatorType.equals(ValidatorType.Regex)) {
				String regex = typedArray
						.getString(R.styleable.ValidatorType_regex_expression);
				((RegexValidator) fieldValidator).setRegex(regex);
			}
		} catch (Exception e) {
			Log.e("ERRO", "Validador nao implementado");
		}
		typedArray.recycle();
	}

	@Override
	protected void onFocusChanged(boolean focused, int direction,
			Rect previouslyFocusedRect) {
		super.onFocusChanged(focused, direction, previouslyFocusedRect);

		if (!focused) {
			validate();
		}
	}

	public void validate() {
		ValidationResult result = fieldValidator.validate(this.getText().toString());
		this.setError(result.getErrorMessage());
	}

}
